<template>
	<view class="container">
		<view class="user">

			<image class="user-icon" @click="navigatorToTake"
				src="https://www.healthshishan.cn/profile/static/image/Left-back.png" mode=""></image>
			<!-- <view class="text">{{ nickname }}</view> -->
			<!-- <view class="text">Ear rot</view> -->
		</view>
		<h1 class="title">Welcome</h1>
		<view class="form-container">
			<uni-forms :modelValue="formData" :rules="rules" ref="formRef">
				<uni-forms-item label="Phone Number" name="tel">
					<uni-easyinput v-model="formData.tel" placeholder="Enter your phone number"
						placeholder-style="color: #ccc;" />
				</uni-forms-item>
				<uni-forms-item label="Password" name="password">
					<uni-easyinput type="password" v-model="formData.password" placeholder="Enter your password"
						placeholder-style="color: #ccc;" />
				</uni-forms-item>
				<view class="button-group">
					<button class="action-btn login-btn" @click="submitDebounced('login')" :disabled="loading">Log
						In</button>
					<view class="button-1">
						<button class="action-btn register-btn" @click="toregister"
							:disabled="loading">Register</button>
						<button class="action-btn" @click="tofind">Forgot Password</button>
					</view>
				</view>
			</uni-forms>
			<view class="footer">

			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive
	} from 'vue';
	// 防抖函数  
	const debounce = (func, delay) => {
		let timer;
		return (...args) => {
			clearTimeout(timer);
			timer = setTimeout(() => {
				func.apply(this, args);
			}, delay);
		};
	};
	const navigatorToTake = () => {
		uni.switchTab({
			url: '/pages/index/index',
		});
	};
	// 优化登录和注册函数  
	const submitDebounced = debounce((action) => submit(action), 500);

	const loading = ref(false);

	// 表单数据
	const formData = reactive({
		tel: '',
		password: '',
	});

	// 跳转到找回密码页面
	const tofind = () => {
		uni.navigateTo({
			url: '/pages/find/find',
		});
	};
	// 跳转到注册页面
	const toregister = () => {
		uni.navigateTo({
			url: '/pages/register/register',
		});
	};
	// Form validation rules  
	const rules = {
		tel: {
			rules: [{
					required: true,
					errorMessage: 'Phone number cannot be empty'
				},
				{
					pattern: /^1[3-9]\d{9}$/,
					errorMessage: 'Please enter a valid phone number'
				},
			],
		},
		password: {
			rules: [{
				required: true,
				errorMessage: 'Password cannot be empty'
			}, ],
		},
	};

	// Form reference  
	const formRef = ref(null);

	const submit = async (action) => {
		try {
			const res = await formRef.value.validate();
			console.log('Validation successful sign', res);

			// After validation passes, perform registration or login based on action  
			if (action === 'register') {
				await handleRegister();
			} else if (action === 'login') {
				await handleLogin();
			}
		} catch (err) {
			console.log('Validation failed', err);
			uni.showModal({
				title: 'error',
				content: 'Validate failed',
				showCancel: false,
			});
		}
	};


	// 登录  
	const handleLogin = async () => {
		loading.value = true;
		try {
			// 检查本地存储的用户信息  
			const userData = await uni.getStorageSync('user-data'); // 获取用户数据  
			if (userData) {
				uni.showModal({
					title: 'Tip',
					content: 'Please log out first',
					showCancel: false,
					confirmText: 'OK'
				});
				loading.value = false; // 重置加载状态  
				return; // 结束函数  
			}
			const res = await uni.request({
				url: 'https://maize.ltd/yumi/login',
				method: 'POST',
				data: {
					"phone": formData.tel,
					"password": formData.password,
				},
			});

			if (res.data.code === 200) {
				await saveToken(res.data.data);
				await savePhone(formData.tel);

				const currentTime = +new Date(); // 获取当前时间戳  
				uni.setStorageSync('lastLoginTime', currentTime); // 存储登录时间  
				uni.showModal({
					title: 'Tip',
					content: 'Login successful',
					showCancel: false,
					confirmText: 'OK'
				});
				uni.switchTab({
					url: '/pages/index/index'
				});
			} else {
				uni.showModal({
					title: 'Tip',
					content: res.data.message || 'Login failed',
					showCancel: false,
					confirmText: 'OK'
				});
			}
		} catch {
			uni.showModal({
				title: 'Tip',
				content: 'Network error',
				showCancel: false,
				confirmText: 'OK'
			});
		} finally {
			loading.value = false; // 重置加载状态  
		}
	};

	// 保存登录令牌，userid，昵称  
	const saveToken = (token) => {
		uni.setStorage({
			key: 'user-data',
			data: token,
			success: () => {
				console.log('用户信息已存储');
			},
		});
	};

	// 保存手机号  
	const savePhone = (phone) => {
		uni.setStorage({
			key: 'phone',
			data: phone,
			success: () => {
				console.log('手机号已存储');
			},
		});
	};
</script>


<style scoped lang="less">
	.user {
		width: 80%;
		// height: 100%;
		position: fixed;
		top: 80rpx;
		left: 15rpx;
		display: flex;
		// align-items: center;
		// justify-content: center;
		padding: 10rpx;
		// border: 3rpx solid black;
		border-radius: 20rpx;
		// background-color: #cff0c8;
		// background-color: pink; // box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
		z-index: 9999;


		.user-icon {

			width: 100rpx;
			height: 100rpx;
			border-radius: 50%;
			margin-right: 80rpx;
			// border: 2rpx solid #000000;
		}

		.text {
			// background-color: #cff0c8;
			font-size: 36rpx;
			font-weight: bold;
			margin-left: 120rpx;
			margin-top: 30rpx;
			// left: 20%;
			// transform: translate(-50%, -50%);
		}

	}

	.button-1 {
		display: flex;
	}

	.container {
		position: relative;
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
		/* 调整为顶部对齐 */
		align-items: center;
		background-color: #f0f0f0;
		color: #333;
		/* 标题颜色 */
		overflow: hidden;
	}

	.title {
		margin-top: 140rpx;
		margin-bottom: 150rpx;
		font-size: 58rpx;
		font-weight: bold;
		text-align: center;
		color: #333;
	}

	.form-container {
		width: 90%;
		max-width: 800rpx;
		padding: 30rpx;
		background-color: #fff;
		border-radius: 12rpx;
		box-shadow: 0 6rpx 12rpx rgba(0, 0, 0, 0.15);
		color: #333;
		text-align: center;
	}

	.uni-forms-item {
		display: flex;
		align-items: center;
		/* 垂直居中 */
		margin-bottom: 32rpx;
		/* 缩小项之间的间距 */
		padding-left: 10rpx;
		/* 调整整个表单项的左边距 */
	}

	.uni-forms-item label {
		text-align: right;
		/* 文本右对齐 */
		font-size: 26rpx;
		color: #333;
	}

	.uni-easyinput {
		padding: 10rpx;
		font-size: 26rpx;
		color: #333;
	}


	.action-btn {

		display: flex;
		align-items: center;
		justify-content: center;
		height: 100rpx;
		width: 100%;
		padding: 5rpx;
		margin-top: 30rpx;
		margin-right: 10rpx;
		font-size: 30rpx;
		border: none;
		border-radius: 6rpx;
		cursor: pointer;
		transition: all 0.3s;
	}

	.register-btn {
		background-color: #28a745;
		color: #fff;
	}

	.register-btn:hover {
		background-color: #218838;
	}

	.login-btn {
		background-color: #007bff;
		color: #fff;
	}

	.login-btn:hover {
		background-color: #0056b3;
	}

	.footer {
		margin-top: 20rrpx;
	}


	.footer-btn:hover {
		color: #0056b3;
	}
</style>